package com.eptok.weixin.action;


import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eptok.weixin.service.CoreService;
import com.eptok.weixin.util.JsonUtil;
import com.eptok.weixin.util.LogUtil;
import com.eptok.weixin.util.SignUtil;

import yspay.express.bean.CheckBean;

@Controller
public class WenxinChatCoreController  {
	private static final Logger log = Logger.getLogger(WenxinChatCoreController.class);
	@Resource
	private CoreService coreService;
	/**
	 * 此方法验证成为开发者
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = { "/wenxinChat.do" }, method = RequestMethod.GET)    
	public @ResponseBody String doGet(HttpServletRequest request, HttpServletResponse response,
			CheckBean bean) {

		log.info("GET进入微信验证");
		
		response.setContentType("text/plain; charset=utf-8"); 
		LogUtil.MSG.info(JsonUtil.object2json(bean));
		if(bean != null) {
			//请求交易
			try {
				if(SignUtil.checkSigntaur(bean.getSignature(), bean.getTimestamp().toString(), bean.getNonce().toString())) {
					LogUtil.MSG.info("验证成功，准备返回");
					return bean.getEchostr();
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		log.info("验证失败，返回error");
		return "error";

	}
	
	/**
	 * 微信接口唯一入口
	 * @param request
	 * @param response
	 * @throws IOException 
	 * 
	 */
	@RequestMapping(value = { "/wenxinChat.do" }, method = RequestMethod.POST)
	public void doPost(HttpServletRequest request, HttpServletResponse response,CheckBean bean)throws IOException {
		
		log.info("接受到微信的POST请求");
		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
//			response.setContentType("application/xml;charset=UTF-8");
			response.setContentType("text/plain; charset=utf-8");
			
			//每次都验证是否是微信发来的消息再处理
			if(SignUtil.checkSigntaur(bean.getSignature(), bean.getTimestamp().toString(), bean.getNonce().toString())) {
				String encryptMsg = coreService.processRequest(request,bean);
				PrintWriter out = response.getWriter();
				out.print(encryptMsg);
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			PrintWriter out = response.getWriter();
			out.print("");
			out.close();
			log.error("回复消息出错",e);
		}
		

	}

}
